<?php
/**
 * tmaic.com 
 * ============================================================================
 * * 版权所有 2020-2030 tmaic，并保留所有权利。
 * 网站地址: http://www.tmaic.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: pangxianfei
 * $email:421339244@qq.com
 * $phone:18929142226
 * $date 2020-11-13
*/
namespace App\Http\Controllers\Admin;


use Illuminate\Http\Request;
use App\Http\Controllers\AdminController;
use App\Models\Order\Order;
use App\Models\Order\Bill;
use App\Models\Refund\Refund;

use App\Models\Order\Goods;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class StatisticsController extends AdminController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
  
       //订单交易金额
       $OrderNumber = Order::pay(1)->whereDay('created_at',Carbon::today())->sum('order_money');
       $OrderMonthNumber = Order::pay(1)->whereMonth('created_at',date("m"))->sum('order_money');

       //$newGoodsNumber = Goods::whereDay('created_at',Carbon::today())->count();
        //成交量
        $TodayOrder['total'] = Order::whereDay('created_at',Carbon::today())->count();
        $TodayOrder['pay'] = Order::pay(1)->whereDay('created_at',Carbon::today())->count();
        //退款统计
        $refundOrder['month'] = Refund::whereMonth('created_at',date('m'))->sum('refund_fee');
        $refundOrder['today'] = Refund::whereDay('created_at',Carbon::today())->sum('refund_fee');

        //提现统计
        $cashoutOrder['month'] = Bill::whereMonth('created_at',date('m'))->sum('order_totals');
        $cashoutOrder['today'] = Bill::where('status','!=',4)->whereDay('created_at',Carbon::today())->sum('order_totals');



        return view('admin.statistics.index', compact('OrderNumber','OrderMonthNumber','TodayOrder','refundOrder'));
    }

 
    public function data(Request $request)
    {

        $username = $request->get('username')??null;
        $phone = $request->get('phone')??null;
        $created_at = $request->get('created_at')??null;     
        $model = Order::query();
        $model = $model->leftJoin('member', 'order.member_id', '=', 'member.id');
        if ($request->get('order_no')) {
            $model = $model->where('order.order_no', 'like', '%' . $request->get('order_no') . '%');
        }

        if ($request->get('status')) {
            $status = $request->get('status');
            switch ($request->get('status'))
            {
                case "1":  $model = $model->where('pay_status',1);  break; //已支付 
                case "2":  $model = $model->where('pay_status',0);  break; //未付款
                case "3":  $model = $model->where('order_status',1);  break; //已完成
                case "4":  $model = $model->where('refund_status',1);  break; //退款订单
                //default:  break;
            }
        }       
        if(!empty($username)){
           $model = $model->where('member.username', 'like', "%{$username}%");
        } 
        
        if(!empty($phone)){
           $model = $model->where('member.moblie', 'like', "%{$phone}%");
        }    
        if(!empty($created_at)){
            $startime = substr($created_at,0,20);
            $endtime =  substr($created_at,-20,20);
            $model = $model->whereBetween('order.created_at',[$startime,$endtime]);
        } 

        $res = $model->orderBy('order.order_id','desc')->paginate(8);//$request->get('limit', 8)

        $data = [
            'code' => 0,
            'msg' => '正在请求中...',
            'count' => $res->total(),
            'data' => $res->items()
        ];
        return response()->json($data);
    }


    public function goodsData(Request $request)
    {
        $model = Goods::query();
        if ($request->get('id')) {
            $model = $model->where('order_id',$request->get('id'));
        }
        $res = $model->orderBy('id','asc')->paginate($request->get('limit', 10));
        $data = [
            'code' => 0,
            'msg' => '正在请求中...',
            'count' => $res['total'],
            'data' => $res->items()
        ];
        return response()->json($data);
    }



    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(UserCreateRequest $request)
    {

        $data = $request->except(['userRole','password_confirmation','_token']);
        $data['uuid'] = \Faker\Provider\Uuid::uuid();
        $data['password'] = bcrypt($data['password']);

        if ($user = User::create($data)) {
            if($request->get('userRole')){
                $roles = explode(',',$request->get('userRole'));
                if ($roles)   $user->syncRoles($roles);
            }
            return response()->json(['code' => 0, 'msg' => '添加用户成功']);
        }
        return response()->json(['code' => 1, 'msg' => '系统错误']);
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $user = User::findOrFail($id);
        return view('admin.order.edit', compact('user'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $id = (int)$request->get('id');
        $user = User::findOrFail($id);
        $data = [];

        DB::beginTransaction();
        /*
        $isUsername = User::where('username', $request->get('username'))->where('id', '!=', $id)->count();
        if ($isUsername) return response()->json(['code' => 1, 'msg' => '账号已存在!']);
        if ($request->get('username') && !$isUsername) {
            $data['username'] = $request->get('username');
        }
        */
        try{

            $isEmail = User::where('email', $request->get('email'))->where('id', '!=', $id)->count();
            if ($isEmail) return response()->json(['code' => 1, 'msg' => '邮箱已存在!']);
            if ($request->get('email') && !$isEmail) {
                $data['email'] = $request->get('email');
            }

            $isPhone = User::where('phone', $request->get('phone'))->where('id', '!=', $id)->count();
            if ($isPhone) return response()->json(['code' => 1, 'msg' => '手机号已存在!']);
            if ($request->get('email') && !$isPhone) {
                $data['phone'] = $request->get('phone');
            }

            $isNickName = User::where('nickName', $request->get('nickName'))->where('id', '!=', $id)->count();
            if ($isNickName) return response()->json(['code' => 1, 'msg' => '用户名已存在!']);
            if ($request->get('email') && !$isNickName) {
                $data['nickName'] = $request->get('nickName');
            }

            if($request->get('userRole')){
                $roles = explode(',',$request->get('userRole'));
                if ($roles)   $user->syncRoles($roles);
            }
            if ($user->update($data)) {
                DB::commit();
                return response()->json(['code' => 0, 'msg' => '更新成功']);
            }

        }catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => 1, 'msg' => '更新失败']);
        }
    }

    /**
     * Update ajax.
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function updateAjax(Request $request)
    {
        $id = $request->get('id');
        $user = User::findOrFail($id);

        $data = $request->except('state');

        if ($user->update($data)) {
            return response()->json(['code' => 0, 'msg' => '状态更新成功']);
        }

        return response()->json(['code' => 1, 'msg' => '状态更新失败']);
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $ids = $request->get('ids');

        if (empty($ids)) {
            return response()->json(['code' => 1, 'msg' => '请选择删除项']);
        }
        if (User::destroy($ids)) {
            return response()->json(['code' => 0, 'msg' => '删除成功']);
        }
        return response()->json(['code' => 1, 'msg' => '删除失败']);
    }

 
 

 
 

}
